package com.jiangyg.mall.gateway.support.security.handler;

import com.jiangyg.mall.core.support.restful.Result;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 类描述：没有访问权限的异常处理
 *
 * @author jiangyg
 * @version 4.0
 * @date 2021-10-11
 */
@Slf4j
public class AccessDeniedExceptionHandler implements ServerAccessDeniedHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        return Mono.defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response -> {
                    Logger.info(log, () -> String.format("请求[%s]没有访问权限异常：", WebUtils.getRequestPath(exchange)), denied);
                    response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                    final String rd = Result.instance("423").toJSONString();
                    final DataBuffer buffer = response.bufferFactory().wrap(rd.getBytes(StandardCharsets.UTF_8));
                    return response.writeWith(Mono.just(buffer)).doOnError(error -> DataBufferUtils.release(buffer));
                });
    }

}
